package com.shengqin.calculate.events.listeners;

import com.shengqin.calculate.data.ErrorLogModel;
import com.shengqin.calculate.events.CalculateLogEvent;
import com.shengqin.entity.CalculateLog;
import com.shengqin.service.ICalculateLogService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Slf4j
@Component
public class CalculateErrorListener {

  @Resource
  private ICalculateLogService calculateLogService;

  @SneakyThrows
  @EventListener(CalculateLogEvent.class)
  @Async
  public void onApplicationEvent(CalculateLogEvent errorLogEvent) {
    ErrorLogModel model = errorLogEvent.getModel();

    try {
      CalculateLog calculateLog = new CalculateLog();
      BeanUtils.copyProperties(model,calculateLog);
      calculateLog.setCreateTime(LocalDateTime.now());
      calculateLogService.saveOrUpdate(calculateLog);
    } catch (Exception e) {
      log.error("记录计算日志报错",e);
    }
  }
}